type Parser = (md: string) => string

const delParser: Parser = (md) => {
  // [^ ]: 不用有空格，eg: ss**weew ewe**
  const myRe = /~~([^ \s\\*]+?)~~/g

  let myArray
  while ((myArray = myRe.exec(md)) !== null) {
    const bold = myArray[1]
    md = md.replace(myArray[0], `<del>${bold}</del>`)
  }
  return md
}

const boldParser: Parser = (md) => {
  // [^ ]: 不用有空格，eg: ss**weew ewe**
  const myRe = /\*\*([^ \s\\*]+?)\*\*/g

  let myArray
  while ((myArray = myRe.exec(md)) !== null) {
    const bold = myArray[1]
    md = md.replace(myArray[0], `<b>${bold}</b>`)
  }
  return md
}

//  ![图片alt](图片URL)
const imgParser: Parser = (md) => {
  const myRe = /!\[([^ ]+)\]\(([^ ]+)\)/g

  let myArray
  while ((myArray = myRe.exec(md)) !== null) {
    const src = myArray[2]
    const alt = myArray[1]
    md = md.replace(myArray[0], `<img src='${src}' alt='${alt}' />`)
  }

  return md
}

export function md2html(md: string): string {
  return delParser(boldParser(imgParser(md)))
}
